﻿/******************************************************************************
 * 创建者：gtts
 * 创建日期：2011.4.10
 * 类名：DragAndDropListener
 * 说明：处理拖放操作的事件侦听器
 ******************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;

namespace GTTSOfLibrary.EventListener
{
    /// <summary>
    /// 处理拖放操作的事件侦听器
    /// </summary>
    public class DragAndDropListener : ListenerBase
    {
        /// <summary>
        /// 对象开始被拖动时被触发
        /// </summary>
        public  event MouseEventHandler StartDragging;

        /// <summary>
        /// 当拖动操作开始后，鼠标移动时触发
        /// </summary>
        public event EventHandler<DraggingMoveEventArgs> DraggingMove;

        /// <summary>
        /// 当拖放操作开始后，松开鼠标时触发
        /// </summary>
        public event MouseEventHandler StopDragging;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="target"></param>
        public DragAndDropListener(Control target)
            : base(target)
        {
            target.MouseDown += new MouseEventHandler(target_MouseDown);
            target.MouseMove += new MouseEventHandler(target_MouseMove);
            target.MouseUp += new MouseEventHandler(target_MouseUp);
        }

        private Point anchor = new Point();
        private Point lastLoction = new Point();
        private bool isDragging = false;

        void target_MouseDown(object sender, MouseEventArgs e)
        {
            anchor = e.Location;
            lastLoction = anchor;
        }

        void target_MouseMove(object sender, MouseEventArgs e)
        {
            if (isDragging==false)
            {
                if (e.Button==MouseButtons.Left)
                {
                    isDragging = true;
                    //开始拖放操作
                    if (StartDragging!=null)
                    {
                        StartDragging(Target, e);
                    }
                }
            }
            if (isDragging==true)
            {
                Size offSet = new Size(e.Location.X-lastLoction.X,
                    e.Location.Y-lastLoction.Y);
//正在拖放，触发DraggingMove事件
                if (DraggingMove!=null)
                {
                    DraggingMove(Target,
                        new DraggingMoveEventArgs(anchor,lastLoction,offSet));
                }
                lastLoction=e.Location;
            }
        }

        void target_MouseUp(object sender, MouseEventArgs e)
        {

            if (isDragging)
            {
                //结束拖放,触发StopDragging事件
                if (StopDragging!=null)
                {
                    StopDragging(Target, e);
                }
            }
        }
    }
}
